﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using WebAPITest.Models.Database;

namespace WebAPITest.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CacheController : ControllerBase
    {
        private readonly IMemoryCache cache;
        private readonly WebEnterpriseIIContext _db;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="cache"></param>
        public CacheController(IMemoryCache cache)
        {
            this.cache = cache;
           
        }


        /// <summary>
        /// 判断缓存是否存在
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<string> TryGetValueCache()
        {
            if(cache.TryGetValue("UserName",out Object obj))
            {
                return "该缓存存在";
            }
            else
            {
                return "该缓存不存在";
            }
        }
        [HttpGet]
        public ActionResult<string> GetCache()
        {
            // 写入缓存
            cache.Set("UserName", "admin");
            cache.Set("Password", "123456");

            //读取缓存
            string userName = cache.Get<string>("UserName");
            string passWord = cache.Get<string>("Password");

            //返回
            return userName + "\n" + passWord;
        }

        [HttpGet]
        public ActionResult<string> GetOrCreateCache()
        {
            string userName = cache.GetOrCreate("UserName", entry =>
            {
                return "admin";
            });
            string password = cache.GetOrCreate("Password", entry =>
            {
                return "123456";
            });
            return userName + "\n" + password;
        }
        [HttpGet]
        public ActionResult<string> RemoveCache()
        {
            cache.Set("UserName", "admin");
            cache.Set("PassWord", "123456");

            cache.Remove("UserName");
            cache.Remove("Password");

            return "缓存删除成功";
        }
        /// <summary>
        /// 永不过期
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<string> CacheTime1()
        {
            string msg = string.Empty;
            cache.Set("UserName", "admin");

            //读取缓存
            for(int i = 1; i <= 5; i++)
            {
                msg += $"第{i}秒缓存值:{cache.Get<string>("UserName")}\n";
                Thread.Sleep(1000);
            }

            return msg;
        }
        [HttpGet]
        public ActionResult<string> CacheTime2()
        {
            string msg = string.Empty;
            cache.Set("UserName", "admin", TimeSpan.FromSeconds(3));

            for(int i = 1; i <= 5; i++)
            {
                msg += $"第{i}秒缓存值：{cache.Get<string>("UserName")}\n";
                Thread.Sleep(1000);
            }
            return msg;
        }
        [HttpGet]
        public ActionResult<string> CacheTime3()
        {
            string msg = string.Empty;
            cache.Set("UserName", "admin", new MemoryCacheEntryOptions
            {
                SlidingExpiration = TimeSpan.FromSeconds(3)
            });
            for(int i = 1; i <= 5; i++)
            {
                msg += $"第{i}秒缓存值：{cache.Get<string>("UserName")}\n";
                Thread.Sleep(1000);
            }
            return msg;
        }




        [HttpGet]
        public List<Good> GetGoodLIst()
        {
            //编写接口获取商品列表数据，并且使用本地缓存保存查询结果，缓存时间为30分钟
            //1、先查看缓存有没有商品数据 key     变量类型和变量名
            if(cache.TryGetValue("GoodCache",out List<Good> goodList))
            {
                //3、如果有则直接返回缓存数据
                return goodList;
            }
            else
            {
                var goods = _db.Goods.Where(x => x.Id > 0).ToList();
                cache.Set("GoodCache", goods, TimeSpan.FromMinutes(30));
                return goods;
            }
            

        }



        [HttpGet]
        public Good GetGoodInfo(int goodId)
        {
            //编写商品详情接口，用户浏览商品详情时使用本地缓存保存登录用户浏览商品记录
            //商品详情
            var good = _db.Goods.FirstOrDefault(x => x.Id == goodId);
            //使用本地缓存保存登录用户浏览商品记录(多个商品)
            var userId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            //之前缓存下来的浏览记录  每个用户浏览记录都是单独的 每个用户都有自己的key 
            var record = cache.Get<List<Good>>($"UserViews{userId}");
            //浏览商品记录
            var views = new List<Good>();
            views.Add(good);

            if (record != null)
                views.AddRange(record);

            cache.Set($"UserViews{userId}", views);
            return good;
        }
    }
}
